// pages/detailPage/detailPage.js
import store from '../../modules/store'
import tool from '../../modules/tool'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPro: true,
    data: {},
    show: false,
    swiperCurrent: 1,
    swiperCurrentNum: 0,
    content: '',
    showPayBoard: 0,
    pd_price: 0,
    pd_priceSingle: 0,
    pd_selectedOptions: {},
    pd_count: 1,
    pd_type: 1,
    form: {}
  },

  handleFormChange(e) {
    this.setData({
      form: e.detail,
      pd_selectedOptions: e.detail
    })
  },

  handlePayNow() {
    if (!this.data.isPro) {
      try {
        tool.handleCheckForm(this.data.form, this.data.data.options)
      } catch (error) {
        tool.handleShowToast(`${error}`, 'error')
        return
      }
    } else {
      let options = this.data.data.options
      let selectedOptions = this.data.pd_selectedOptions
      for (let i = 0; i < options.length; i++) {
        if (options[i].required) {
          if (selectedOptions[options[i].title] === undefined) {
            tool.handleShowToast(`请选择${options[i].title}`)
            return
          }
        }
      }
    }

    let t = this.properties.data
    t.itemId = t.id
    t.isPro = this.data.isPro ? 1 : 0
    t.num = this.data.pd_count
    t.priceWithFloatDisplay = tool.formatPrice(t.price)
    t.priceWithFloatDisplayTotal = tool.formatPrice(t.price * t.num)
    // delete t.id
    t.options = this.data.pd_selectedOptions
    tool.handleShowPayPage([t])
  },

  handleShowCart() {
    wx.navigateBack({
      delta: 10
    })
    tool.handleShowCart()
  },

  handleInputUserName(e) {
    e = e.detail.value
    let t = this.data.pd_selectedOptions
    t.name = e
    this.setData({
      pd_selectedOptions: t
    })
  },

  handleInputWeChat(e) {
    e = e.detail.value
    let t = this.data.pd_selectedOptions
    t.wechat = e
    this.setData({
      pd_selectedOptions: t
    })
  },

  async handleAddToCart() {
    if (!this.data.isPro) {
      try {
        tool.handleCheckForm(this.data.form, this.data.data.options)
      } catch (error) {
        tool.handleShowToast(`${error}`, 'error')
        return
      }
    } else {
      let options = this.data.data.options
      let selectedOptions = this.data.pd_selectedOptions
      for (let i = 0; i < options.length; i++) {
        if (options[i].required) {
          if (selectedOptions[options[i].title] === undefined) {
            tool.handleShowToast(`请选择${options[i].title}`)
            return
          }
        }
      }
    }
    let re = await tool.handleAddToCart(this.data.isPro ? 1 : 0, this.data.data.id, this.data.pd_count, this.data.pd_priceSingle, this.data.pd_selectedOptions)
    if (re) {
      tool.handleShowToast('添加成功', 'success')
      tool.handleUpdateCartNum()
      this.handleHidePayBoard()
    }
  },

  handleHidePayBoard() {
    this.setData({
      showPayBoard: 0
    })
  },

  handleChangeCount(e) {
    e = e.currentTarget.dataset
    let t = this.data.pd_count
    if (e.up) {
      t++
    } else {
      t--
    }
    if (t < 1) t = 1
    this.setData({
      pd_count: t
    })
    this.pd_updatePrice()
  },

  handleOptionClick(e) {
    e = e.currentTarget.dataset
    if (e.selected) {
      let t = this.data.pd_selectedOptions
      delete t[e.item]
      this.setData({
        pd_selectedOptions: t
      })
      this.pd_updatePrice()
      return
    }
    let t = this.data.pd_selectedOptions
    t[e.item] = e.subitem
    this.setData({
      pd_selectedOptions: t
    })
    this.pd_updatePrice()
  },

  pd_updatePrice() {
    let data = this.data.pd_selectedOptions
    let p = this.data.data.price
    for (let i = 0; i < Object.keys(data).length; i++) {
      let value = data[Object.keys(data)[i]]
      let key = Object.keys(data)[i]
      if (!this.data.data.options) continue
      for (let i1 = 0; i1 < this.data.data.options.length; i1++) {
        if (this.data.data.options[i1].title == key) {
          let ind = this.data.data.options[i1].items.indexOf(value)
          if (ind + 1) {
            p += this.data.data.options[i1].prices[ind]
          }
        }
      }
    }
    let item = {
      price: p * this.data.pd_count
    }
    this.setData({
      pd_priceSingle: p,
      pd_price: (item.price / 100).toString() + ((item.price / 100).toString().split('.')[1] ? ((item.price / 100).toString().split('.')[1].length == 1 ? '0' : '') : '')
    })
  },

  handleBuyClick() {
    if(!tool.isLogined()){
      tool.handleNotLogin()
      return
    }
    this.pd_updatePrice()
    this.setData({
      showPayBoard: 1,
      pd_type: 1
    })
  },

  handleShowPLUS(){
    if(tool.isLogined()){
      wx.navigateTo({
        url: '/pages/vip/vip',
      })
    }else{
      tool.handleNotLogin()
    }
  },

  handleAddToCartClick() {
    if(!tool.isLogined()){
      tool.handleNotLogin()
      return
    }
    this.pd_updatePrice()
    this.setData({
      showPayBoard: 1,
      pd_type: 2
    })
  },

  onShareAppMessage() {
    console.log({
      path: "/pages/index/index?" + `isPro=${this.data.isPro}&id=${this.data.data.id}&type=share`,
      title: `${this.data.data.title} ￥${this.data.data.priceDisplay}`,
      imageUrl: this.data.data.imageUrl[this.data.swiperCurrentNum] ? (this.data.imagePrefix + this.data.data.imageUrl[this.data.swiperCurrentNum]) : (this.data.imagePrefix + 'startLogo.png'),
    })
    return {
      path: "/pages/index/index?" + `isPro=${this.data.isPro}&id=${this.data.data.id}&type=share`,
      title: `${this.data.data.title} ￥${this.data.data.priceDisplay}`,
      imageUrl: this.data.data.imageUrl[this.data.swiperCurrentNum] ? (this.data.imagePrefix + this.data.data.imageUrl[this.data.swiperCurrentNum]) : (this.data.imagePrefix + 'startLogo.png'),
      success(res) {
        console.log('分享成功', res);
      },
      fail(err) {
        console.log('分享失败', err);
      }
    }
  },

  handleSwiperChange(e) {
    try {
      e.detail.current
    } catch (error) {
      e = {
        detail: {
          current: 0
        }
      }
    }
    this.setData({
      swiperCurrent: `${e.detail.current + 1}/${this.data.data.imageUrl.length}`,
      swiperCurrentNum: e.detail.current
    })
  },

  handlePreview() {
    let re = JSON.parse(JSON.stringify(this.data.data.imageUrl))
    for (let i = 0; i < re.length; i++) {
      re[i] = this.data.imagePrefix + re[i]
    }
    wx.previewImage({
      urls: re,
      current: this.data.imagePrefix + this.data.data.imageUrl[this.data.swiperCurrentNum]
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    // wx.showShareMenu({
    //   withShareTicket: true // 是否带上转发信息（可选）
    // });
    console.log(options)
    if (store.getItem('windowInfo') == undefined) {
      console.log(4321, options)
      return
    }
    tool.setPageData(this)
    let t = store.getItem('detailPageData')
    if (!t) {
      wx.navigateBack()
      return
    }
    this.setData(t)
    wx.setNavigationBarTitle({
      title: t.data.title
    })
    store.removeItem('detailPageData')
    if (this.data.data.content) {
      this.setData({
        content: await tool.getContent(this.data.data.content)
      })
    }
    this.setData({
      show: true
    })
    this.handleSwiperChange()

    store.onChange('detailPageHidePayBoard', () => {
      this.setData({
        showPayBoard: 0
      })
    })

    //购物车
    this.setData({
      cartNum: store.getItem('cartNum'),
    })
    store.onChange('cartNum', () => {
      this.setData({
        cartNum: store.getItem('cartNum'),
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})